﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MultiThreading
{
    public partial class PeriodEndProcessing : Form
    {
        public PeriodEndProcessing()
        {
            InitializeComponent();
        }
        IJob job = new Job();
        private void btnProcess_Click(object sender, EventArgs e)
        {
            if (bgWorker.IsBusy)
                return;
            refreshStatusTimer.Enabled = true;
            lblProgress.Visible = true;
            progressBar.Visible = true;
            lblStatus.Visible = true;
            btnCancel.Enabled = false;
            btnProcess.Enabled = false;
            bgWorker.RunWorkerAsync();
        }
        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //bgWorker.ReportProgress(10, null);            
            job.Execute();
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                //The user canceled the operation.               
            }
            else if (e.Error != null)
            {              
                string msg = String.Format("An error occurred: {0}", e.Error.Message);                
            }
            refreshStatusTimer.Enabled = false;
            lblProgress.Visible = false;
            progressBar.Visible = false;
            lblStatus.Visible = false;
            btnCancel.Enabled = true;
            btnProcess.Enabled = true;
        }

        private void refreshStatusTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                object[] status = job.GetExecuteStatus();

                if (status != null)
                {
                    int totalCount = Convert.ToInt32(status[0]);
                    int completedCount = Convert.ToInt32(status[1]);
                    string itemInProcess = Convert.ToString(status[2]);

                    this.progressBar.Maximum = totalCount;
                    this.progressBar.Value = completedCount;

                    if (!string.IsNullOrEmpty(itemInProcess))
                        this.lblStatus.Text = string.Format("Processing Item: {0}", itemInProcess);
                   
                }
            }
            catch
            {
            }
        }
    }
}
